﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.OleDb;
using System.Configuration;
using System.IO;

namespace DocumentManager
{
    public partial class Form1 : Form
    {
        public String ConnectionString = ConfigurationManager.ConnectionStrings["DocumentManager.Properties.Settings.TrainingCertificationsConnectionString"].ConnectionString;

        public Form1()
        {
            InitializeComponent();
        }

//        private void btnSubmit_Click(object sender, EventArgs e)
//        {
//            tsLabelMessage.Visible = false;
//            tsErrorMessage.Visible = false;

//            if (txtManNumber.Text.Trim().Length == 0)
//            {
//                //MessageBox.Show("Man Number is required.");
//                tsErrorMessage.Text = "A Man Number is required.";
//                tsErrorMessage.Visible = true;
//                return;
//            }
//            //Validate that man number exists in users table
//            if (!UserExists(txtManNumber.Text.Trim()))
//            {
//                //MessageBox.Show("Man Number " + txtManNumber.Text + " does not exist. Please contact a Flight Cheif or Systems Administrator.");
//                tsErrorMessage.Text = "Man Number " + txtManNumber.Text + " does not exist. Please contact a Flight Chief or Systems Administrator.";
//                tsErrorMessage.Visible = true;
//                return;
//            }

//            if (txtDescription.Text.Trim().Length == 0)
//            {
//                //MessageBox.Show("A Description is required.");
//                tsErrorMessage.Text = "A Description is required.";
//                tsErrorMessage.Visible = true;
//                return;
//            }
//            if (txtFile.Text.Trim().Length == 0)
//            {
//                //MessageBox.Show("A File is required.");
//                tsErrorMessage.Text = "A File is required.";
//                tsErrorMessage.Visible = true;
//                return;
//            }
//            String ManNumber = txtManNumber.Text.Trim();

//            if (ManNumber.Length != 5)
//            {
//                ManNumber = ManNumber.PadLeft(5, '0');
//                txtManNumber.Text = ManNumber;
//            }
//            //assume datetime picker is correct, hopefully user changed it?
//            String Sql = @"Insert into Documents (Description, Document, Created_Date, Man_Number, Course_Date) 
//                                      values (@Description,@Document,@CreatedDate,@ManNumber,@CourseDate)";
//            //Sql = @"Insert into Documents @(Document, Man_Number, Created_Date, Description) 
//                                      //values (@Document, @ManNumber, @CreatedDate, @D)";
//            OleDbConnection con = new OleDbConnection(ConnectionString);

//            OleDbCommand com = con.CreateCommand();
//            try
//            {
//                FileInfo fileInfo = new FileInfo(txtFile.Text);
//                if (!fileInfo.Exists)
//                {
//                    tsErrorMessage.Text = "File no longer exists, please select a new file.";
//                    tsErrorMessage.Visible = true;
//                    //MessageBox.Show("File no longer exists, please select a new file.");
//                    return;
//                }
//                byte[] fileData = null;
//                // Read file data into buffer
//                using (FileStream fs = fileInfo.OpenRead())
//                {
//                    fileData = new byte[fileInfo.Length];
//                    int nReadLength = fs.Read(fileData, 0, (int)(fileInfo.Length));
//                }

//                com.CommandText = Sql;
//                com.Parameters.AddWithValue("@Description", txtDescription.Text.Trim());
//                com.Parameters.AddWithValue("@Document", fileData);                
//                com.Parameters.AddWithValue("@CreatedDate", DateTime.Now.ToOADate());
//                int mNumber = Int16.Parse(ManNumber);
//                com.Parameters.AddWithValue("@ManNumber", mNumber);
//                com.Parameters.AddWithValue("CourseDate", dateTimePicker1.Value.ToOADate());

//                con.Open();

//                int result = com.ExecuteNonQuery();
//                if (result > 0)
//                {
//                    //MessageBox.Show("Inserted record.");
//                    tsLabelMessage.Text = "Record successfully created for " +ManNumber+ ".";
//                    tsLabelMessage.Visible = true;
//                    txtDescription.Text = String.Empty;
//                    txtFile.Text = String.Empty;
//                    dateTimePicker1.ResetText();
//                }
//                else
//                {
//                    MessageBox.Show("Error. Contact Application Administrator.");
//                }
//            }
//            catch (Exception ex)
//            {
//                //error
//                MessageBox.Show("Error. Contact Application Administrator.");
//            }
//            finally
//            {
//                con.Close();
//            }
//        }

        //private void textBox4_TextChanged(object sender, EventArgs e)
        //{

        //}

        //private void txtFile_Click(object sender, EventArgs e)
        //{
        //    if (openFileDialog1.ShowDialog() == DialogResult.Cancel)
        //    {
        //        return;
        //    }
        //    String filePath = openFileDialog1.FileName;
        //    if (filePath == "")
        //        return;

        //    if (System.IO.File.Exists(filePath) == false)
        //        return;
        //    else
        //        txtFile.Text = filePath;
        //}



//        private void button1_Click(object sender, EventArgs e)
//        {
//            //test, to create a user real quick

//            String Sql = @"Insert into Users (Man_Number, User_Name, Role_ID, Created_Date, Created_By,Flight) 
//                                      values (00763,'Jesse Barrus',1,'01/01/2011','00763', 'B')";
//            OleDbConnection con = new OleDbConnection(ConnectionString);

//            OleDbCommand com = con.CreateCommand();
//            try
//            {
//                com.CommandText = Sql;
//                con.Open();
//                int result = com.ExecuteNonQuery();
//                if (result > 0)
//                {
//                    MessageBox.Show("Inserted record.");
//                }
//                else
//                {
//                    MessageBox.Show("Error");
//                }
//            }
//            catch (Exception ex)
//            {
//                //error
//            }
//            finally
//            {
//                con.Close();
//            }
//        }

        private void miAdminLogin_Click(object sender, EventArgs e)
        {
            tsLabelMessage.Visible = false;
            tsErrorMessage.Visible = false;

            //Form1 form = new Form1();
            //AddDocument addDoc = new AddDocument();
            //addDoc.MdiParent = form;
            //addDoc.Show();

            //Show passphrase form
            using (Login login = new Login())
            {
               // login.MdiParent = this;
                login.Bounds = new Rectangle(10, 10, 306, 90);
                login.ShowDialog();

                Boolean result = login.IsAdmin;

                //If is admin, change menus around, providing additional features
                if (result)
                {
                    menuStrip1.Visible = false;
                    menuStrip2.Visible = true;
                    tsLabelMessage.Text = "Now logged in as Admin.";
                    tsLabelMessage.Visible = true;
                }
                else
                {
                    tsErrorMessage.Text = "Unable to authenticate user.";
                    tsErrorMessage.Visible = true;
                }
            }
        }


        //read
        /*(
         *      SqlCommand command =
            new SqlCommand(queryString, connection);
        connection.Open();

        SqlDataReader reader = command.ExecuteReader();

        // Call Read before accessing data.
        while (reader.Read())
        {
            Console.WriteLine(String.Format("{0}, {1}",
                reader[0], reader[1]));
        }

        // Call Close when done reading.
        reader.Close();b
         * */

        #region Public methods for all forms
        public void HideStatusBarMessages()
        {
            tsErrorMessage.Visible = false;
            tsLabelMessage.Visible = false;
        }
        public void WriteErrorMessage(String Message)
        {
            tsErrorMessage.Text = Message;
            tsErrorMessage.Visible = true;
        }
        public void WriteOtherMessage(String Message)
        {
            tsLabelMessage.Text = Message;
            tsLabelMessage.Visible = true;
        }

        public Boolean UserExists(String ManNumber)
        {
            //ToDo 

            //Make sure man number is only numbers
            int tempNumber = -1;
            Boolean isNumber = int.TryParse(ManNumber, out tempNumber);
            if (!isNumber)
            {
                //MessageBox.Show("Man Number must be numeric");
                return false;
            }
            //lPAD WITH ZEROS
            if (ManNumber.Length != 5)
            {
                ManNumber = ManNumber.PadLeft(5, '0');

            }
            //1) Hit the DB and see if a row is returned with this//1) Hit the DB and see if a row is returned with this//1) Hit the DB and see if a row is returned with this
            Boolean result = false;
            OleDbConnection connection = new OleDbConnection(ConnectionString);
            OleDbCommand command = connection.CreateCommand();
            command.CommandText = "select Man_Number from Users where Man_Number = " + ManNumber;
            connection.Open();
            OleDbDataReader reader = command.ExecuteReader();
            reader.Read();
            if (reader.HasRows) result = true;
            else result = false;
            reader.Close();
            connection.Close();

            return result;
        }

        #endregion

        private void vToolStripMenuItem_Click(object sender, EventArgs e)
        {
            tsLabelMessage.Visible = false;
            tsErrorMessage.Visible = false;
            if (!isAlreadyOpen("UsersDocuments"))
            {
                UsersDocuments usersDocs = new UsersDocuments();
                usersDocs.MdiParent = this;
                usersDocs.Show();
            }
        }


        private Boolean isAlreadyOpen(String FormName)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.Name == FormName)
                {
                    form.Focus();
                    return true;
                }
            }
            return false;
        }
        private void documentsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //Populate the list of windows to show
            List<ToolStripItem> items = new List<ToolStripItem>();

            foreach (ToolStripItem tsi in documentsToolStripMenuItem.DropDown.Items)
            {
                if (!tsi.Text.Trim().Equals(String.Empty))
                {
                    items.Add(tsi);
                }
                else
                {
                    break;
                }
            }

            //Add Base Menus
            documentsToolStripMenuItem.DropDown.Items.Clear();
            foreach (ToolStripItem tsi in items)
            {
                documentsToolStripMenuItem.DropDown.Items.Add(tsi);
            }

            //Add seperator
            ToolStripSeparator tss = new ToolStripSeparator();
            documentsToolStripMenuItem.DropDown.Items.Add(tss);

            //Add other existing open windows
            foreach (Form form in Application.OpenForms)
            {
                if (form.Name != "Form1" && form.Text != "Documents By User" && form.Text != "Documents By Flight")
                {
                    ToolStripMenuItem tsi = new ToolStripMenuItem();
                    tsi.Text = form.Text;
                    tsi.Click += new EventHandler(DynamicEventClick);
                    documentsToolStripMenuItem.DropDown.Items.Add(tsi);
                    //MessageBox.Show("Form owned:" + form.Name);
                }
            }
        }

        private void DynamicEventClick(object sender, EventArgs e)
        {
            ToolStripItem item = (ToolStripItem)sender;
            foreach(Form form in Application.OpenForms)
            {
                if (item.Text == form.Text)
                {
                    form.Focus();
                }
            }
        }

        private void maintainUsersToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (!isAlreadyOpen("MaintainUsers"))
            {
                MaintainUsers maintainDocs = new MaintainUsers();
                maintainDocs.MdiParent = this;
                maintainDocs.Show();
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }
    }
}
